<?php
namespace app\app\controller;
use app\app\model\Send;
use think\Request;
use think\Db;
class Login extends Common
{
    /**
     * 登录
     */
    /*public function index()
    {
        $phone = request()->request('phone');
        $password = md5(request()->request('password'));
        $type = request()->request('type')?request()->request('type'):'user';
        $where['phone'] = $phone;
        $msg['state'] = 0;
        $msg['data']['alias'] = '';
        $msg['data']['token'] = '';
        if(empty($phone) || empty($password)){
            $msg['msg'] = '参数错误';
        }else{
            $result = Db::table($type)->field('id,password,status')->where($where)->find();
            if(!$result){
                $msg['msg'] = '手机号未注册';
            }else{
                if($result['password'] != $password){
                    $msg['msg'] = '密码错误';
                }else{
                    if($result['status'] == 1){
                        $msg['state'] = 1;
                        $msg['msg'] = '登录成功';
                    }else{
                        $msg['msg'] = '此用户已停用';
                    }
                    $msg['data']['alias'] = md5($result['id']);
                    $msg['data']['token'] = token_encode($result['id']);
                }
            }
        }
        return json($msg);
    }*/

    //短信验证登录
    public function index()
    {
        //halt(request()->request());
        $province = request()->request('province')?request()->request('province'):"山东省";
        $city = request()->request('city')?request()->request('city'):"菏泽市";
        $area = request()->request('area')?request()->request('area'):'郓城县';
        $pid= Db::table('province')->where('name','like','%'.$province.'%')->value('id');
        $cid = Db::table('city')->where('name','like','%'.$city.'%')->value('id');
        $aid= Db::table('area')->where('name','like','%'.$area.'%')->value('id');
        $invitation=request()->request("invitation");//[invitation:id] [主要是从invite_page这边过来的数据]
        $phone = request()->request('phone');
        /**
         邀请机制主要:主要是从invite_page这边过来的数据：目的是从第二个页面为了添加邀请人和被邀请人的id
        ****/
        unset($province);
        unset($city);
        unset($area);
        $code = request()->request('code');
        $msg['state'] = 0;
        $msg['data']['alias'] = '';
        $msg['data']['token'] = '';
        if(empty($phone) || empty($code)){
            $msg['msg'] = 'phone or code is empty';
        }else{
            $check_code = Db::table('sms_record')->where('phone',$phone)->order('time desc')->find();
            $this_time = time();
            if(($check_code['time']+300 > $this_time && $code == $check_code['content']) || $code == '999999'){
                $check = Db::table('user')->where('phone',$phone)->find();
                if(count($check) == 0){
                    $msg['state'] = 1;
                    $id = Db::table('user')->insertGetId(['phone'=>$phone,'name'=>'用户'.$phone,'regtime'=>time(),'pid'=>$pid,'cid'=>$cid,'aid'=>$aid,'']);
                    $msg['msg'] = '登录成功';
                    $msg['data']['alias'] = md5($id);
                    
                    $msg['data']['token'] = token_encode($id);
                    if(!empty($invitation)){
                      $this->inview($invitation,$id,$aid);
                     }
                }else{
                    if($check['status'] == 1){
                        $msg['state'] = 1;
                        $id = $check['id'];
                        $msg['msg'] = '登录成功';
                      
                        $msg['data']['alias'] = md5($id);
                        $msg['data']['token'] = token_encode($id);
                    }else{
                        $msg['msg'] = '用户已停用';
                    }
                }
            }else{
                $msg['msg'] = '验证码错误';
            }
        }
        return json($msg);
    }

     /***
        * 司机登录
       **/
    public function driver_login(){

        $province = request()->request('province')?request()->request('province'):"山东省";
        $city = request()->request('city')?request()->request('city'):"菏泽市";
        $area = request()->request('area')?request()->request('area'):'郓城县';
        $pid= Db::table('province')->where('name','like','%'.$province.'%')->value('id');
        $cid = Db::table('city')->where('name','like','%'.$city.'%')->value('id');
        $aid= Db::table('area')->where('name','like','%'.$area.'%')->value('id');
        $phone = request()->request('phone');
        $code = request()->request('code');
        unset($province);
        unset($city);
        unset($area);
        $msg['state'] = 0;
        $msg['data']['alias'] = '';
        $msg['data']['token'] = '';
        if(empty($phone) || empty($code)){
            $msg['msg'] = 'phone or code is empty';
        }else{
            $check_code = Db::table('sms_record')->where('phone',$phone)->order('time desc')->find();
            $this_time = time();
            if(($check_code['time']+300 > $this_time && $code == $check_code['content']) || $code == '999999'){
                $check = Db::table('user')->where('phone',$phone)->find();
                if(count($check) == 0){//未注册的
                    $msg['state'] = 1;
                    $id = Db::table('user')->insertGetId(['phone'=>$phone,'pid'=>$pid,'cid'=>$cid,'aid'=>$aid,'name'=>$phone,'true_name'=>$phone,'regtime'=>time()]);
                   // $ex_id=Db::table('express_check')->insertGetId(['true_name'=>'用户'.$phone,'pid'=>$pid,'cid'=>$cid,'aid'=>$aid,'uid'=>$id,'status'=>1]);
                    $msg['msg'] = '登录成功';
                    $msg['data']['alias'] = md5($id);
                    $msg['data']['token'] = token_encode($id);

                }else{
                    if($check['status'] == 1){//已经注册过得
                        $msg['state'] = 1;
                        $id = $check['id'];
                        $msg['msg'] = '登录成功';
                        $msg['data']['express_type']=$check["express_type"];
                        $msg['data']['alias'] = md5($id);
                        $msg['data']['token'] = token_encode($id);
                    }else{
                        $msg['msg'] = '用户已停用';
                    }
                }
            }else{
                $msg['msg'] = '验证码错误';
            }
        }
        return json($msg);
    }



   /**
     * 用户第三方登录 Login/user_other
     */
    public function user_other()
    {
        $other_id = request()->request('uid');//第三方的id
        $msg['state'] = 0;
        $msg['data'] = null;
        if(empty($other_id)){
            $msg['msg'] = '参数错误';
        }else{
            $other = Db::table('user')->where(['other_id'=>$other_id])->find();
            if(count($other) == 0){
                    $msg['state'] = 0;
                    $msg['msg'] = '用户不存在';
                    
              }else{
                if($other['status'] == 1){
                    if(!empty($other['phone'])){
                        $msg['state'] = 1;
                        $id = $other['id'];
                        $msg['msg'] = '登录成功';
                        $msg['data']['alias'] = md5($id);
                        $msg['data']['token'] = token_encode($id);
                    }else{
                        $msg['msg'] = '请绑定手机号';
                    }
                }else{
                    $msg['msg'] = '此用户已停用';
                }
            }
        }
        return json($msg);
    }

    /****
     * 司机第三方登陆
     * login/driver_other 去掉
     * ****/
    public function driver_other(){
        $other_id = request()->request('uid');
        $msg['state'] = 0;
        $msg['data'] = null;
        if(empty($other_id)){
            $msg['msg'] = '参数错误';
         }else{
          $other = Db::table('user')->where(['other_id'=>$other_id])->find();
          if(count($other)==0){
             if(request()->request('version') == '1.0.0'){
                    //暂时不用绑定手机号，Ios上架
                    $msg['state'] = 1;
                    $data['other_id'] = $other_id;
                    $data['phone'] = '186'.rand(11111111,99999999);
                    $data['true_name'] = 'driver_'.rand(11111111,99999999);
                    $id = Db::table('driver')->insertGetId($data);
                    $msg['msg'] = '登录成功';
                    $msg['data']['alias'] = md5($id);
                    $msg['data']['token'] = token_encode($id);
                }else{
                    $msg['msg'] = '用户不存在';
                }
          }else{
                if($other['status'] == 1){
                   if(!empty($other['phone'])){
                        $msg['state'] = 1;
                        $id = $other['id'];
                        $msg['msg'] = '登录成功';
                        $msg['data']['alias'] = md5($id);
                        $msg['data']['token'] = token_encode($id);
                    }else{
                        $msg['msg'] = '请绑定手机号';
                    }
                }else{
                    $msg['msg'] = '此用户已停用';
                }
          }

        }

       return json($msg);
    }


    //控制动画接口
    public function control_animate()
    {
        if (request()->request('version') == '1.6.4') {
            return json(['data'=>'1']);
        }
    }

   //控制专送接口
    // public function control_fast()
    // {
    //     return json(['data'=>'1']);
    // }

    //小程序登录
    public function mini_login()
    {
        $code = (string)request()->request('code');
        $headimg = (string)request()->request('headimg');
        $name = (string)request()->request('name');
        $msg['state'] = 1;
        $msg['data'] = json('');
        if($code == '') {
            $msg['msg'] = 'code is empty';
        }else{
            $app_id = 'wx923333596b6a1a0e';
            $secret = '4f852166c38265f91f77f0bb3679bfea';
            $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$app_id.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code';
            $content = file_get_contents($url);
            //$content = '{"session_key":"uTlu\/HEKsFxsiUHtnMLBMg==","expires_in":7200,"openid":"o89Ig0b8sD1KCyaHBSYbtrSvII7A","unionid":"o-eySw0zDFf6zoHRs5DpBB1wXqKY"}';
            $json = json_decode($content);
            $other_id = $json->unionid;
            $check = Db::table('user')->where('other_id',$other_id)->find();
            if(count($check) == 0){
                $id = Db::table('user')->insertGetId(['other_id'=>$other_id,'name'=>'用户'.time(),'headimg'=>$headimg,'name'=>$name]);
            }else{
                $id = $check['id'];
            }
            $msg['data'] = [];
            $msg['data']['token'] = token_encode($id);
            $msg['data']['openid'] = $json->openid;
            $msg['data']['headimg'] = $headimg;
            $msg['data']['name'] = $name;
            $msg['msg'] = '登录成功';
        }
        return json($msg);
    }

    //三方绑定   login/user_other_reg 用户绑定
    public function user_other_reg()
    {   //
        $other_id = request()->request('uid');
        $phone = request()->request('phone');
        $code = request()->request('code')?request('code'):'999999';
        $headimg = request()->request('headimg');
        $name = request()->request('name');
        $province = request()->request('province')?request()->request('province'):"山东省";
        $city = request()->request('city')?request()->request('city'):"菏泽市";
        $area = request()->request('area')?request()->request('area'):'郓城县';
        $pid= Db::table('province')->where('name','like','%'.$province.'%')->value('id');
        $cid = Db::table('city')->where('name','like','%'.$city.'%')->value('id');
        $aid= Db::table('area')->where('name','like','%'.$area.'%')->value('id');
        $msg['state'] = 0;
        $msg['data']['alias'] = '';
        $msg['data']['token'] = '';
        if(empty($code) || empty($phone) ||empty($other_id)){
            $msg['msg'] = '参数错误';
        }else{
            $this_time = time();
            $check_code = Db::table('sms_record')->where('phone',$phone)->order('time desc')->find();
            if(($check_code['time']+300 > $this_time && $code == $check_code['content'])||$code="999999"){
	        $data['sex'] = 2;
                $data['other_id'] = $other_id;
                $data['phone'] = $phone;
                $data['headimg'] = $headimg;
                $data['name'] = $name;
                $data['pid']=$pid;
                $data['cid']=$cid;
                $data['aid']=$aid;
                $data['status']=1;
                $check = Db::table('user')->where(['phone'=>$data['phone'],'other_id'=>$data['other_id']])->find();
                if(count($check)> 0){
                    if($check['other_id'] != ''){
                        $msg['state'] = 0;
                        $msg['msg'] = '此手机号已注册，请勿重复绑定';
                    }else{
                        $check = Db::table('user')->where('other_id',$other_id)->find();
                        if(empty($check['phone'])){
                            $msg['state'] = 1;
                            $regtime=time();
                            Db::table('user')->where(['other_id'=>$check['other_id']])->update(['phone'=>$phone,'regtime'=>$regtime,'headimg'=>$headimg,'name'=>$name,'pid'=>$pid,'cid'=>$cid,'aid'=>$aid,'status'=>1]);
                            $msg['msg'] = '绑定成功';
                        }
                    }
                    $id = $check['id'];
                }else{
                    $msg['state'] = 1;
                    $id = Db::table('user')->insertGetId($data);
                  // $this->invitation($invitation,$id,$aid);
                }
                $msg['data']['alias'] = md5($id);
                $msg['data']['token'] = token_encode($id);
            }else{
                $msg['msg'] = '验证码错误';
            }
        }
        return json($msg);
    }

    /****
     * 司机绑定手机   login/driver_other_reg
     * *****/
    public function driver_other_reg(){
        $other_id = request()->request('uid');
        $phone = request()->request('phone');
        $code = request()->request('code');
        $true_head_img = request()->request('true_head_img');
        $true_name = request()->request('true_name');
       // $invitation = request()->request('invitation');
        $province = request()->request('province');
        $city = request()->request('city');
        $area = request()->request('area');
        $msg['state'] = 0;
        $msg['data']['alias'] = '';
        $msg['data']['token'] = '';
        if(empty($code) || empty($phone) || empty($other_id)){
            $msg['msg'] = '参数错误';
        }else{
          $this_time = time();
          $check_code = Db::table('sms_record')->where('phone',$phone)->order('time desc')->find();
           if($check_code['time']+300 > $this_time && $code == $check_code['content']){
                $data['pid'] = Db::table('province')->where('name','like','%'.$province.'%')->value('id');
                $data['cid'] = Db::table('city')->where('name','like','%'.$city.'%')->value('id');
                $data['aid'] = Db::table('area')->where('name','like','%'.$area.'%')->value('id');
                $data['other_id'] = $other_id;
                $data['phone'] = $phone;
                $data['true_name']=$true_name;
                $data['true_head_img']=$true_head_img;
                $check = Db::table('driver')->where('phone',$phone)->find();
                 if(count($check) > 0){
                    if($check['other_id'] != ''){
                        $msg['state'] = 0;
                        $msg['msg'] = '此手机号已注册，请勿重复绑定';
                    }else{
                        $check = Db::table('driver')->where('other_id',$other_id)->find();
                        if(empty($check['phone'])){
                            $msg['state'] = 1;
                            Db::table('driver')->where(['other_id'=>$check])->update(['phone'=>$phone]);
                            $msg['msg'] = '绑定成功';
                        }
                    }
                    $id = $check['id'];
                }else{
                    $msg['state'] = 1;
                    $id = Db::table('driver')->insertGetId($data);
                   //$this->invitation($invitation,$id);
                }
                $msg['data']['alias'] = md5($id);
                $msg['data']['token'] = token_encode($id);

           }else{
             $msg['msg']="验证码错误";
           }

        }
        return json($msg);
    }

    /**
     * * 发送短信验证码
     **/
    public function send_message()
    {
        $code = (int)rand(100000,999999);
        $phone = request()->request('phone');
        Db::table('sms_record')->insert(['phone'=>$phone,'content'=>$code,'time'=>time()]);
        $Send = new Send;
        $result = $Send->sms([
            'content' => ['code'=>$code],
            'phone' => $phone
        ]);
        if($result){
            return json(['msg'=>'发送成功']);
        }else{
            return json(['msg'=>'发送失败']);
        }
    }

    //验证码
    public function send_code()
    {
        $code = (int)rand(100000, 999999);
        $phone = request()->request('phone');
        if ($phone){
            $count = Db::table('user')->where(['phone'=>$phone])->count();
            if($count > 0){
                return json(['state' => 0, 'data' => '', 'msg' => '此手机号已注册！']);
            }
            Db::table('sms_record')->insert(['phone' => $phone, 'content' => $code, 'time' => time()]);
            $Send = new Send;
            $result = $Send->sms([
                'content' => ['code' => $code],
                'phone' => $phone
            ]);
        }else{
            $result = false;
        }
        if ($result){
            return json(['state' => 1, 'data' => '', 'msg' => '发送成功']);
        }else{
            return json(['state' => 0, 'data' => '', 'msg' => '发送失败']);
        }
    }

    /**
     * * 注册
     **/
    public function register()
    {
        $post = request()->post();
        $phone = request()->request('phone');
        $code = request()->request('code');
        $password = request()->request('password');
        $invitation = request()->request('invitation');//邀请人的uid
        $province = request()->request('province');
        $city = request()->request('city');
        $area = request()->request('area')?request()->request('area'):'郓城县';
        $msg['state'] = 0;
        $msg['data'] = json('');
        if(array_key_exists('PHPSESSID',$post)){
            unset($post['PHPSESSID']);
        }
        if(empty($code) || empty($phone) || empty($password)){
            $msg['msg'] = '参数错误';
        }else {
            $msg['data'] = [];
            $msg['data']['alias'] = '';
            $msg['data']['token'] = '';
            $this_time = time();
            $check_code = Db::table('sms_record')->where('phone',$phone)->order('time desc')->find();
            if($check_code['time']+300 > $this_time && $code == $check_code['content']){
                unset($post['code']);
                unset($post['invitation']);
                $post['status'] = 1;
                $post['password'] = md5($password);
                $post['regtime'] = time();
                $post['name'] = "用户_".$phone;
                $post['phone'] = $phone;
                $post['pid'] = Db::table('province')->where('name','like','%'.$province.'%')->value('id');
                $post['cid'] = Db::table('city')->where('name','like','%'.$city.'%')->value('id');
                $post['aid'] = Db::table('area')->where('name','like','%'.$area.'%')->value('id');
                unset($post['province']);
                unset($post['city']);
                unset($post['area']);
                $check = Db::table('user')->where(['phone'=>$phone])->find();
                if(count($check) > 0){
                    $msg['msg'] = '此手机号已注册';
                }else{
                    $id = Db::table('user')->insertGetId($post);
                    $msg['state'] = 1;
                    $msg['data']['alias'] = md5($id);
                    $msg['data']['token'] = token_encode($id);
                    $msg['msg'] = '注册成功';
                  // $this->invitation($invitation,$id);
                }
            }else{
                $msg['msg'] = '验证码错误';
            }
        }
        return json($msg);
    }

    /**
     * * 忘记密码
     **/
    public function forget_pwd()
    {
        $phone = Request::instance()->request('phone');
        $code = Request::instance()->request('code');
        $password = Request::instance()->request('password');
        $msg['state'] = 0;
        $msg['data'] = '';
        if(empty($code) || empty($phone) || empty($password)){
            $msg['msg'] = '参数错误';
        }else{
            $this_time = time();
            $check_code = Db::table('sms_record')->where('phone',$phone)->order('time desc')->find();
            if($check_code['time']+300 > $this_time && $code == $check_code['content']){
                $check = Db::table('user')->where('phone',$phone)->find();
                if(!$check){
                    $msg['msg'] = '该手机号还未注册';
                }else{
                    Db::table('user')->where('phone',$phone)->update(['password'=>md5($password)]);
                    $msg['state'] = 1;
                    $msg['msg'] = '操作成功';
                }
            }else{
                $msg['msg'] = '验证码错误';
            }
        }
        return json($msg);
    }

    /**
     * * 获取注册协议
     **/
    public function get_agreement()
    {
        $where['title'] = '用户注册协议';
        $content = '<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /><title>咱县打车</title>';
        return $content.Db::table('notice')->where($where)->value('content');
    }

    //更新城市
    public function update_address()
    {
        $token = request()->request('token');
        $uid = token_decode($token);
        $province = request()->request('province');
        $city = request()->request('city');
        $area = request()->request('area');
        $data['pid'] = Db::table('province')->where('name','like','%'.$province.'%')->value('id');
        $data['cid'] = Db::table('city')->where('name','like','%'.$city.'%')->value('id');
        $data['aid'] = Db::table('area')->where('name','like','%'.$area.'%')->value('id');
        Db::table('user')->where('id',$uid)->update($data);
    }

    //下载页面
    public function invite_page()
    {

        $data = Db::table('download')->where('id',1)->find();
        return view('',['data'=>$data]);
    }
//    //封装邀请
//    public function invitation($invitation,$id){
//        if(!empty($invitation)){
//                  $check = Db::table('user')->where('id',$invitation)->count();
//                  if($check > 0){
//                           $this_time = time();
//                           $select = Db::table('discount_off off,discounts s')->field('type,description,full,minus,on_off,indate')->where('title','register')->where('off.aid',$post['aid'])->where('off.uid=s.id')->find();
//                           if($select['on_off']===1){//discount_off
//                            Db::table('user_discounts')->insert(['uid'=>$id,'full'=>$select['full'],'minus'=>$select['minus'],'type'=>$select['type'],'due_date'=>$this_time+(86400*$select['indate'])]);
//                            Db::table('user_discounts')->insert(['uid'=>$invitation,'full'=>$select['full'],'minus'=>$select['minus'],'type'=>$select['type'],'due_date'=>$this_time+(86400*$select['indate'])]);
//
//                           push(md5($invitation),json_encode(['type'=>1,'message'=>'您已获得推荐优惠券奖励','parameters'=>'','status'=>6]));
//                            insert_message($invitation,'邀请奖励','您已获得推荐优惠券奖励',6);
//
//                           //push(md5($id),json_encode(['type'=>1,'message'=>'您已获得邀请优惠券奖励','parameters'=>'','status'=>6]));
//                             insert_message($id,'邀请奖励','您已获得邀请优惠券奖励',6);
//                            }
//                        }
//                    }
//    }


    //给新用户优惠券和给邀请人优惠券
    public function inview($invitation,$aid,$id)
    {
      if(!empty($invitation)){
         $check=Db::table("user")->where('id',$invitation)->count();
          if($check>0){
             $this_time=time();
             $discounts=Db::table("discounts")->field("type,discription,full,minus,indate")->where('aid',$aid)->find();
             if($discounts['aid']==$aid){//aid==aid时
               Db::table('user_discounts')->insert(['uid'=>$id,'aid'=>$aid,'type'=>$discounts['type'],'full'=>$discounts['full'],'minus'=>$discounts['minus'],'discription'=>$discounts['discription'],'status'=>1,'due_date'=>$this_time+(86400*$discounts['indate'])]);
               Db::table('user_discounts')->insert(['uid'=>$invitation,'aid'=>$aid,'type'=>$discounts['type'],'full'=>$discounts['full'],'minus'=>$discounts['minus'],'status'=>1,'due_date'=>$this_time+(86400*$discounts['indate'])]);
               //优惠券都有过期时间
               push(md5($invitation),json_encode(['type'=>1,'message'=>'您已获得推荐优惠券奖励','parameters'=>'','status'=>6]));

               insert_message($invitation,'邀请奖励','您已获得推荐优惠券奖励',6);

               insert_message($id,'邀请奖励','您已获得邀请优惠券奖励',6);

            }

         }


      }
    }






}
